static public int InversePairs(int [] array) {
if(array==null||array.length==0)
{
return 0;
}
int [] result = new int[array.length];
int a= Merge(array, result, 0, array.length - 1)%1000000007;
System.out.println(Arrays.toString(result));
return a;
}
public static int Merge(int [] arr,int [] result,int start , int end)
{
if (start==end)
{
result[start]= arr[start];
return 0;
}
int mid = (end+start)>>1;
int left = Merge(arr,result,start,mid)%1000000007;
int right = Merge(arr,result,mid+1,end)%1000000007;
左结束,右结束
结果数组的下标index;
逆序数 count
*/
int leftend = mid;
int rightend = end;
int index = end;
int count = 0;
while (leftend>=start&&rightend>mid)
{
if (arr[leftend]>arr[rightend])
{
result[index--]=arr[leftend--];
count+= rightend-mid;
if(count>=1000000007)
{
count%=1000000007;
}
}
else
result[index--]=arr[rightend--];
}
for (;leftend>=start; leftend--)
{
result[index--]=arr[leftend];
}
for (;rightend>mid; rightend--)
{
result[index--] = arr[rightend];
}
for (int i = start;i<=end;i++)
{
arr[i]=result[i];
}
return (count+left+right)%1000000007;
}